<template>
  <div class="table-container">
    <el-row :gutter="10">
      <el-col :lg="4" :md="8" :sm="24" :xl="4" :xs="24">
        <el-card class="box-card" shadow="never">
          <el-tree
            ref="myTree"
            class="custom-tree"
            style="overflow-y: auto; height: 400px"
            :data="userTreeData"
            :default-expanded-keys="['root']"
            node-key="id"
            :highlight-current="true"
            :props="defaultProps"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node }" class="custom-tree-node">
              <span>
                <i class="el-icon-user-solid" />
                {{ node.label }}
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :lg="20" :md="16" :sm="24" :xl="20" :xs="24">
        <el-card class="box-card" shadow="never">
          <el-row :gutter="20">
            <el-col :span="6">
              <div>
                <el-statistic title="工单数" :value="totalData.totalNum" group-separator=",">
                  <template slot="suffix">
                    <i class="el-icon-s-flag" style="color: blue"></i>
                  </template>
                </el-statistic>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <el-statistic title="完成数" :value="totalData.totalFinishNum" group-separator=",">
                  <template slot="suffix">
                    <i class="el-icon-s-flag" style="color: #67c23a"></i>
                  </template>
                </el-statistic>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <el-statistic title="客户需求数" :value="totalData.totalCustomerNum" group-separator=",">
                  <template slot="suffix">
                    <i class="el-icon-star-on" style="color: #f56c6c"></i>
                  </template>
                </el-statistic>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <el-statistic title="完成率" group-separator=",">
                  <template slot="suffix">
                    <i class="el-icon-data-line" style="color: #1296db"></i>
                  </template>
                  <template slot="formatter">
                    {{ totalData.totalNum && ((totalData.totalFinishNum / totalData.totalNum) * 100).toFixed(2) }}%
                  </template>
                </el-statistic>
              </div>
            </el-col>
          </el-row>
        </el-card>
        <el-row type="flex" justify="end" :gutter="10">
          <el-col :span="14">
            <el-date-picker
              v-model="currentWeek"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="handleChange"
              :clearable="false"
            ></el-date-picker>
            <el-button type="info" @click="reset" style="margin-left: 10px">重置</el-button>
          </el-col>
          <el-col :span="3">
            <el-select v-model="queryForm.state" placeholder="请选择工单状态">
              <el-option label="全部" :value="''"></el-option>
              <el-option label="未完成" :value="1"></el-option>
              <el-option label="已完成" :value="2"></el-option>
              <el-option label="取消" :value="3"></el-option>
            </el-select>
          </el-col>
          <el-col :span="7">
            <el-form ref="form" :inline="true" :model="queryForm" @submit.native.prevent>
              <el-form-item>
                <el-input v-model="queryForm.title" placeholder="费用号/项目名称" />
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-search" native-type="submit" type="primary" @click="handleQuery">查询</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-table
          ref="tableSort"
          :data="list"
          :element-loading-text="elementLoadingText"
          :height="height"
          :row-class-name="tableRowClassName"
          border
        >
          <el-table-column label="序号" show-overflow-tooltip width="50">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="费用号" prop="costNumber" show-overflow-tooltip />
          <el-table-column label="项目名称" prop="projectName" show-overflow-tooltip />
          <el-table-column label="工单内容" prop="workContent" show-overflow-tooltip min-width="120" />
          <el-table-column label="客户需求" prop="isCustomerDemand">
            <template #default="{ row }">
              {{ row.isCustomerDemand == 1 ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column label="工单下达时间" prop="workOrderIssuanceTime" show-overflow-tooltip min-width="100" />
          <el-table-column label="执行人" prop="executUserName" />
          <el-table-column label="完成情况">
            <template #default="{ row }">
              <el-tag type="success" effect="dark" v-if="row.completionStatus == 2">已完成</el-tag>
              <el-tag type="info" effect="dark" v-else-if="row.completionStatus == 3">取消</el-tag>
              <el-tag type="" effect="dark" v-else>未完成</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="完成时间" prop="completionTime" show-overflow-tooltip min-width="100" />
          <el-table-column label="工单等级" prop="levelName" sortable min-width="100" />
          <el-table-column label="未关闭原因" prop="notClosingReason" show-overflow-tooltip min-width="100" />
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="{ row }">
              <el-button type="text" @click="handleEdit(row)">编辑</el-button>
              <el-button type="text" @click="handleDelete(row)">删除</el-button>
              <el-button type="text" @click="handleFinish(row)">完成</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :background="background"
          :current-page="queryForm.pageNo"
          :layout="layout"
          :page-size="queryForm.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </el-col>
    </el-row>
    <table-edit ref="edit" @refreshTable="changeData" />
  </div>
</template>

<script>
  import { getAllWorkOrderListBy, deleteWorkOrder, finishWorkOrder, getWorkOrderTotalByuserId, getUserGroup } from '@/api/wordOrder'
  import TableEdit from './components/TableEdit'
  export default {
    name: 'all',
    components: {
      TableEdit,
    },
    data() {
      return {
        userTreeData: [
          {
            id: '',
            realname: '全部用户',
            children: [],
          },
        ],
        defaultProps: {
          children: 'children',
          label: 'realname',
        },
        currentWeek: [],
        totalData: {
          totalNum: '',
          totalFinishNum: '',
          totalWeekNum: '',
          totalWeekFinishNum: '',
        },
        imgShow: true,
        list: [],
        imageList: [],
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: true,
        selectRows: '',
        elementLoadingText: '正在加载...',
        queryForm: {
          userId: '',
          startDate: '',
          endDate: '',
          pageNo: 1,
          pageSize: 20,
          title: '',
          state: '',
        },
        timeOutID: null,
      }
    },
    watch: {
      'queryForm.state'(newValue, oldValue) {
        this.fetchData()
      },
    },
    computed: {
      height() {
        return this.$baseTableHeight()
      },
    },
    created() {
      this.init()
    },
    beforeDestroy() {},
    mounted() {},
    methods: {
      init() {
        this.fetchData()
        this.fetchBarData()
        this.dealUserTree()
      },
      changeData() {
        this.fetchData()
        this.fetchBarData()
      },
      reset() {
        this.currentWeek = []
        this.queryForm = {
          userId: '',
          startDate: '',
          endDate: '',
          pageNo: 1,
          pageSize: 20,
          title: '',
          state: '',
        }
        this.init()
      },
      getNewDay(dateTemp, days) {
        var dateTemp = dateTemp.split('-')
        var nDate = new Date(dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]) //转换为MM-DD-YYYY格式
        var millSeconds = Math.abs(nDate) + days * 24 * 60 * 60 * 1000
        var rDate = new Date(millSeconds)
        var year = rDate.getFullYear()
        var month = rDate.getMonth() + 1
        if (month < 10) month = '0' + month
        var date = rDate.getDate()
        if (date < 10) date = '0' + date
        return year + '-' + month + '-' + date
      },
      handleChange(data) {
        this.queryForm.startDate = data[0]
        this.queryForm.endDate = data[1]
        this.queryForm.state = ''
        this.queryForm.title = ''
        this.init()
      },
      tableSortChange() {
        const imageList = []
        this.$refs.tableSort.tableData.forEach((item, index) => {
          imageList.push(item.img)
        })
        this.imageList = imageList
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleAdd() {
        this.$refs['edit'].showEdit()
      },
      handleEdit(row) {
        this.$refs['edit'].showEdit(row)
      },
      handleDelete(row) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const { msg } = await deleteWorkOrder({ id: row.id })
          this.$baseMessage(msg, 'success')
          this.changeData()
        })
      },
      handleFinish(row) {
        this.$baseConfirm('你确定要完成当前项吗', null, async () => {
          const { msg } = await finishWorkOrder({ id: row.id })
          this.$baseMessage(msg, 'success')
          this.changeData()
        })
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      handleQuery() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        const { data, total } = await getAllWorkOrderListBy(this.queryForm)
        this.list = data
        this.total = total
      },
      async fetchBarData() {
        const { data } = await getWorkOrderTotalByuserId(this.queryForm)
        this.totalData = data
      },
      tableRowClassName({ row, rowIndex }) {
        if (row.completionStatus == 2) {
          return 'success-row'
        } else if (row.completionStatus == 3) {
          return 'info-row'
        }
        return ''
      },
      //处理用户树
      async dealUserTree() {
        const { data } = await getUserGroup()
        this.userTreeData[0].children = data
      },
      handleNodeClick(data) {
        console.log(data)
        this.queryForm.state = ''
        this.queryForm.title = ''
        this.queryForm.userId = data.id
        this.fetchData()
        this.fetchBarData()
      },
    },
  }
</script>
<style lang="scss">
  .el-icon-user-solid {
    color: #409eff;
  }
  .custom-tree .el-tree-node__content:hover {
    background-color: #4ecb73 !important; /* 更改为需要的高亮颜色 */
    color: #fff;
    .el-icon-user-solid {
      color: #fff;
    }
  }
  .custom-tree .is-current > .el-tree-node__content {
    background-color: #4ecb73 !important; /* 更改为需要的高亮颜色 */
    color: #fff;
    .el-icon-user-solid {
      color: #fff;
    }
  }

  .el-table .info-row {
    background: #f0f0f0;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
